package window;

import com.alibaba.fastjson.JSONObject;
import constants.TemplateType;
import cookie.ProjectCookie;
import cookie.TemplateSetting;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import language.Language;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.ProjectUtil;

import java.io.IOException;
import java.util.List;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * create at 2016/11/15 17:03
 */
public class AddTemplateWindow {

    private static final Logger logger = LoggerFactory.getLogger(AddTemplateWindow.class);

    private final ComboBox templateTypeComboBox = new ComboBox();

    private final TextArea templateContent = new TextArea("");

    private final Label templateNameLabel = new Label(Language.getTranslation("template.name"));

    private final TextField templateNameTextField = new TextField();

    private final Label templateExtensionLabel = new Label(Language.getTranslation("template.extension"));

    private final TextField templateExtensionTextField = new TextField();

    private final ButtonBar templateButtonBar = new ButtonBar();

    private ProjectCookie projectCookie;

    private static final String encoding = "UTF-8";

    private String templateType;

    public void init(Stage ownnerStage, String templateType) {

        this.templateType = templateType;

        Stage stage = new Stage();
        stage.setTitle(templateType == TemplateType.CLIENT ? Language.getTranslation("add.client.template") : Language.getTranslation("add.server.template"));//"新建客户端模板" : "新增服务端模板"
        stage.getIcons().add(new Image("app.logo.png"));
        stage.initOwner(ownnerStage);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setWidth(800);
        stage.setHeight(500);
        stage.setMaximized(false);
        stage.setResizable(false);

        templateTypeComboBox.getItems().addAll(TemplateType.getTemplateTypes());
        templateTypeComboBox.setValue(templateType);
        templateTypeComboBox.setDisable(true);

        templateNameTextField.setPromptText(Language.getTranslation("prompt.template.name"));
        templateNameTextField.setMaxWidth(128);

        templateExtensionTextField.setPromptText(Language.getTranslation("prompt.template.extension"));
        templateExtensionTextField.setMaxWidth(128);

        this.templateContent.setPromptText(Language.getTranslation("prompt.template.content"));
        this.templateContent.setMinWidth(784);
        this.templateContent.setMinHeight(392);
        this.templateContent.setWrapText(true);

        Button okButton = new Button(Language.getTranslation("ok"));
        okButton.setDefaultButton(true);
        okButton.setOnAction(event -> {
            if (StringUtils.isNotBlank(templateNameTextField.getText()) && StringUtils.isNotBlank(templateExtensionTextField.getText()) && StringUtils.isNotBlank(templateContent.getText())) {
                this.projectCookie = ProjectCookie.getProjectCookie();
                List<String> templateTypes = ProjectCookie.getTypes(this.projectCookie, this.templateType);
                List<TemplateSetting> templateSettings = this.projectCookie.getTemplateSettings();
                if (templateTypes.contains(templateNameTextField.getText())) {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.initOwner(stage);
                    alert.setTitle(Language.getTranslation("prompt"));//提示
                    alert.setHeaderText(null);
                    alert.setContentText(Language.getTranslation("prompt.template.exist"));//"该模板已经存在！"
                    alert.showAndWait();
                    templateNameTextField.requestFocus();
                } else {
                    TemplateSetting templateSetting = new TemplateSetting();
                    templateSetting.setName(templateNameTextField.getText());
                    templateSetting.setExtension(templateExtensionTextField.getText());
                    templateSettings.add(templateSetting);
                    templateTypes.add(templateNameTextField.getText());
                    try {
                        FileUtils.writeStringToFile(ProjectUtil.getCookieFile("ProjectCookie.json"), JSONObject.toJSONString(this.projectCookie), encoding);
                        FileUtils.writeStringToFile(ProjectUtil.getTemplateFile(templateType, templateNameTextField.getText()), templateContent.getText(), encoding);
                        FileUtils.writeStringToFile(ProjectUtil.getSourceTemplateFile(templateType, templateNameTextField.getText()), templateContent.getText(), encoding);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                    stage.close();
                }
            }
        });

        Button cancelButton = new Button(Language.getTranslation("cancel"));
        cancelButton.setOnAction(event -> stage.close());

        // Add buttons to the ButtonBar
        this.templateButtonBar.getButtons().addAll(okButton, cancelButton);

        HBox hBox = new HBox();
        hBox.setPadding(new Insets(3, 0, 0, 0));
        hBox.setSpacing(8);
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.getChildren().addAll(this.templateTypeComboBox, this.templateNameLabel, this.templateNameTextField, this.templateExtensionLabel, this.templateExtensionTextField);

        GridPane grid = new GridPane();
        grid.setVgap(8);
        grid.setHgap(8);
        grid.setPadding(new Insets(5, 5, 5, 5));
        grid.addRow(0, hBox);
        grid.addRow(1, this.templateContent);
        grid.addRow(2, this.templateButtonBar);

        Scene scene = new Scene(new Group(), 800, 300);
        Group root = (Group) scene.getRoot();
        root.getChildren().add(grid);
        stage.setScene(scene);

        Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
        stage.setX((primScreenBounds.getWidth() - stage.getWidth()) / 2);
        stage.setY((primScreenBounds.getHeight() - stage.getHeight()) / 2);

        stage.showAndWait();
    }

}
